package com.elf.zero.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.ProgressBar;

import com.elf.zero.app.R;

public class ProgressBarWidget extends ProgressBar {

    private final static int default_bg_color = Color.LTGRAY;
    private final static int default_progress_color = Color.RED;
    private final static int default_corner_radius = 5;

    private int bgColor = default_bg_color;
    private int progressColor = default_progress_color;
    private int cornerRadius = default_corner_radius;

    public ProgressBarWidget(Context context) {
        this(context, null);
    }

    public ProgressBarWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ProgressBarWidget);
            bgColor = typedArray.getColor(R.styleable.ProgressBarWidget_background_color, default_bg_color);
            progressColor = typedArray.getColor(R.styleable.ProgressBarWidget_progress_color, default_progress_color);
            cornerRadius = typedArray.getDimensionPixelSize(R.styleable.ProgressBarWidget_corner_radius, default_corner_radius);
            typedArray.recycle();
        }
        setStyle();
    }

    private void setStyle() {
        GradientDrawable bgDrawable = new GradientDrawable();
        bgDrawable.setCornerRadius(cornerRadius);
        bgDrawable.setColor(bgColor);

        GradientDrawable progressDrawable = new GradientDrawable();
        progressDrawable.setCornerRadius(cornerRadius);
        progressDrawable.setColor(progressColor);
        ClipDrawable progressClip = new ClipDrawable(progressDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);

        Drawable[] progressDrawables = {bgDrawable, progressClip};
        LayerDrawable layerDrawable = new LayerDrawable(progressDrawables);
        layerDrawable.setId(0, android.R.id.background);
        layerDrawable.setId(1, android.R.id.progress);
        setProgressDrawable(layerDrawable);
    }

    public void setBgColor(int color) {
        this.bgColor = color;
        setStyle();
    }

    public void setProgressColor(int color) {
        this.progressColor = color;
        setStyle();
    }
}
